package pers.hl.module_main.bookshelf

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ObjectUtils
import kotlinx.android.synthetic.main.fragment_book_shelf.*
import pers.hl.common.base.BaseVBVMFragment
import pers.hl.common.base.IFragment
import pers.hl.module_main.common.PageHelper
import pers.hl.module_main.databinding.FragmentBookShelfBinding
import pers.hl.module_main.main.MainFragment
import pers.hl.module_main.publish.PublishActivity
import pers.hl.module_main.search.BookAdapter

class BookShelfFragment: BaseVBVMFragment<FragmentBookShelfBinding, BookShelfViewModel>(), IFragment,
    MainFragment.OnBarIconClickListener {

    companion object {
        const val RQ_PUBLISH_BOOK = 0x01
    }

    private lateinit var adapter: BookAdapter

    override fun initView(savedInstanceState: Bundle?) {
        initRefresh()
        initRvAdapter()
    }

    private fun initRefresh() {
        mBinding.refreshLayout.apply {
            setEnableLoadMore(false)
            setOnRefreshListener {
                lazyLoadData()
            }
        }
    }

    private fun initRvAdapter() {
        rvBookShelf.layoutManager = LinearLayoutManager(mContext)
        adapter = BookAdapter(mutableListOf())
        rvBookShelf.adapter = adapter
        adapter.notifyDataSetChanged()
        adapter.setOnItemClickListener { _, _, position ->
            val data = this.adapter.getItem(position)
            PageHelper.startBookDetailPage(mContext, data)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun name(): String {
        return "书架"
    }

    override fun onTitleBarIconClick() {
        startActivityForResult(Intent(mContext, PublishActivity::class.java), RQ_PUBLISH_BOOK)
    }

    override fun enableLazyLoad(): Boolean {
        return true
    }

    override fun lazyLoadData() {
        showLoading()
        loadMyBooks()
    }

    private fun loadMyBooks() {
        mViewModel.loadMyShelfBooks().observe(this, Observer {
            hideLoading()
            if (ObjectUtils.isEmpty(it)) {
                adapter.setEmptyView()
            } else {
                adapter.setList(it)
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RQ_PUBLISH_BOOK) {
                loadMyBooks()
            }
        }
    }

    override fun showLoading() {
        mBinding.refreshLayout.autoLoadMoreAnimationOnly()
    }

    override fun hideLoading() {
        mBinding.refreshLayout.finishRefresh()
    }

}